package com.ufida.ids.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class Dom4jUtil {
	
	public static String getXML(JSONArray ja){
		Document document = DocumentHelper.createDocument();
	    Element root = document.addElement("fields");
		for(int i = 0; i<ja.size(); i++){
			JSONObject j = (JSONObject)ja.get(i);
			Element e = root.addElement("field");
			e.addAttribute("name", j.opt("propertyName")+"");
			e.addAttribute("value", j.opt("propertyValue")+"");
		}
		System.out.println(root.asXML());
		return root.asXML();
	}
	
	public static String getJSON(String sourceStr) throws Exception{
		Document document_src = DocumentHelper.parseText(sourceStr);//源字符串
        Element root_src = document_src.getRootElement();//得到根节点
        List l = root_src.elements("field");
        
        List newL = new ArrayList();
        
        for(int i= 0;i<l.size();i++){
        	Map m = new HashMap();
        	Element e = (Element)l.get(i);
        	m.put("propertyName", e.attributeValue("name"));
        	m.put("propertyValue", e.attributeValue("value"));
        	newL.add(m);
        }
        
        JSONObject jo = new JSONObject();
        jo.put("rows", newL);
        jo.put("total", newL.size());
        
        String retStr = jo.toString();
        System.out.println(retStr);
        return retStr;
	}
	
	
	public static void main(String[] args) {
		
		
		try {
			getJSON("<fields><field name=\"cc\" value=\"cc\"></field></fields>");
			
//			Document document_src = DocumentHelper.parseText("<Fields><Field name=\"123\" value=\"456\"/><Field name=\"456\" value=\"789\"/></Fields>");//源字符串
////			System.out.println("document_src:"+document_src.asXML());
//	        Element root_src = document_src.getRootElement();//得到根节点
////	        System.out.println("document_src:"+root_src.asXML());
//	        List l = root_src.elements("Field");
//	        
//	        for(int i= 0;i<l.size();i++){
//	        	Element e = (Element)l.get(i);
//	        	System.out.println(e.attributeValue("name"));
//	        	System.out.println(e.attributeValue("value"));
//	        }
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
		
	}

}
